package cn.cvs.controller;

import cn.cvs.entity.Fruit;
import cn.cvs.service.FruitService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class FruitController {

    @Autowired
    private FruitService fruitService;

    @GetMapping("/list")
    public String list(Model model){

        List<Fruit> list=fruitService.list();

        model.addAttribute("list",list);

        return "list";
    }

    @GetMapping("/fruit/{id}")
    public String view(Model model, @PathVariable(value = "id") Integer id){
        Fruit fruit=fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }

    @ResponseBody
    @GetMapping("/view/{id}")
    public Fruit viewJson(@PathVariable(value = "id") Integer id){/*
*/        Fruit fruit=fruitService.selectById(id);
//        String jsonString= JSON.toJSONString(fruit);
        return fruit;
    }

    //@ResponseBody 将返回的内容放入响应体中
    @ResponseBody
    @DeleteMapping("/fruit/{id}")
    public String delete(@PathVariable Integer id){
        int result=fruitService.delete(id);
        if (result>0){
            return "success";
        }
        return "error";
    }


//    @ResponseBody
//    @PostMapping(value = "/add",produces = {"text/html;charset=UTF-8"})
    @PostMapping("/add")
    public String add(HttpServletRequest request, Model model, @Valid Fruit fruit, BindingResult bindingResult, MultipartFile filePic)throws IOException {
        if (bindingResult.hasFieldErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors){
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
//                System.out.println(fieldError.getField()+":"+fieldError.getDefaultMessage());
            }
            return "add";
        }
        //d:/323/uplood/aaa.jpg
        //目录d:/323/uplood/
        String directory=request.getSession().getServletContext().getRealPath("statics");
        //文件名aaa.jpg
        String fileName= RandomUtils.nextInt(1000000)+"_pic";

        String suffix= FilenameUtils.getExtension(filePic.getOriginalFilename());


        fileName=fileName+"."+suffix;
        //完整的文件路径
        String path=directory+File.separator+fileName;

        File targetFile = new File(path);
        if (!targetFile.exists()){
            targetFile.mkdirs();
        }

        //transferTo传输的意思/转移的意思
        filePic.transferTo(targetFile);
        fruit.setPic(fileName);
        int result = fruitService.add(fruit);
        if (result>0){
            //新增成功
            return "redirect:list";
        }
        model.addAttribute("fruit",fruit);
        return "add";
    }

    @ResponseBody
    @GetMapping("/checkType")
    public String checkType(String type){
        Fruit fruit=fruitService.selectByType(type);
        if (fruit==null){
            return "false";
        }
        return "true";
    }
}
